package com.hsmw.schedule.task;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyun.dyvmsapi20170525.models.SingleCallByVoiceResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.hsmw.schedule.mapper.*;
import com.hsmw.schedule.service.*;
import com.hsmw.schedule.utils.GaoDeInfoUtils;
import com.hsmw.schedule.utils.TencentPushUtils;
import com.hsmw.schedule.vo.DriverUserSortVo;
import com.htn.common.core.constant.*;
import com.hsmw.schedule.utils.CommonUtils;
import com.htn.common.core.util.SendSmsUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.GpsInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @author WD
 * @version 1.0
 * @description: TODO
 * @date 2021/3/1 10:34
 */
@Component
@EnableScheduling
@Configuration
@Slf4j
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderScheduledTask {

	@Autowired
	private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;
	@Autowired
	private HsmwOrderService hsmwOrderService;
	@Autowired
	private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;
	@Autowired
	private HsmwItemService hsmwItemService;
	@Autowired
	private HsmwVehicleService hsmwVehicleService;
	@Autowired
	private HsmwDriverNewsService hsmwDriverNewsService;
	@Autowired
	private HsmwRequestVehicleService hsmwRequestVehicleService;
	@Autowired
	private HsmwHtnUserMapper hsmwHtnUserMapper;
	@Autowired
	private HsmwMonitorDriverMessageMapper hsmwMonitorDriverMessageMapper;
	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;

	@Value(value = "${sms.appKey}")
	private String appKey;
	@Value(value = "${sms.channel}")
	private String channel;
	@Value(value = "${sms.smsSign}")
	private String smsSign;
	@Value(value = "${sms.appId}")
	private int appId;
	@Value(value = "${sms.orderTemplateId}")
	private int orderTemplateId;

	@Value(value = "${sms.driverTemplateId}")
	private int driverTemplateId;

	@Value(value = "${sms.orderTimeoutNoticeBiz}")
	private int orderTimeoutNoticeBiz;

	@Value(value = "${sms.textOrderTimeOut}")
	private int textOrderTimeOut;

	@Value(value = "${sms.orderStatusIsSeven}")
	private int orderStatusIsSeven;


	final static String voiceCode = "0e7fe15a-5f6a-412f-8172-9f324d8c3bce.wav";

	@Autowired
	private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

	@Autowired
	private HsmwUserDriverService hsmwUserDriverService;

	@Autowired
	private HsmwPumpOperateRecordService hsmwPumpOperateRecordService;
	@Autowired
	private HsmwVehicleMapper hsmwVehicleMapper;

	@Autowired
	private HsmwCorporationCompanyMapper hsmwCorporationCompanyMapper;
	@Autowired
	HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper ;


	@Autowired
	private HsmwHtnUserService hsmwHtnUserService;



	/**
	 * 派单定时任务
	 */
	@Async("order")
	@Scheduled(cron = "0 */1 * * * ?")
	@Transactional
	public void executeAppointHsmwOrders() {
		Long begin = System.currentTimeMillis();
		List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequests = hsmwOrderVehicleRequestMapper.selectUnCompleteReqlist();
		//分别对每一个需求进行派单
		if(CollectionUtil.isNotEmpty(hsmwOrderVehicleRequests)){
			hsmwOrderVehicleRequests.stream().forEach(hsmwOrderVehicleRequest->{
				HsmwOrder order = hsmwOrderService.getHsmwOrderById(hsmwOrderVehicleRequest.getOrderId());
				HsmwHtnUser user = hsmwHtnUserMapper.selectById(order.getCreateUser());
				//如果是 指定司机的订单
				if(CommonConstants.YES.equals(hsmwOrderVehicleRequest.getAppointOrder()) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAppointVehicleId())){
					HsmwVehicle vehicle = hsmwVehicleMapper.selectById(hsmwOrderVehicleRequest.getAppointVehicleId());
					//指定派单的时候 必须得保证该车的状态是空闲中
					if(CommonConstants.VEHICLE_FREE.equals(vehicle.getWorkStatus())){
						//如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
						if (hsmwOrderVehicleRelationService.checkIfVehicleWorking(hsmwOrderVehicleRequest.getAppointVehicleId())) {
							//如果是指定车辆的下单 那么 车上的司机 空闲中和接单中的司机 必须大于0 最小是1
							List<HsmwUserDriver> hsmwUserDriverList = hsmwUserDriverService.selectAvaliableList(vehicle.getId());
							if(CollectionUtil.isNotEmpty(hsmwUserDriverList) ){
								//创建子订单信息
								HsmwOrderVehicleRelation hsmwOrderVehicleRelation = new HsmwOrderVehicleRelation();
								String relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
								hsmwOrderVehicleRelation.setVehicleId(hsmwOrderVehicleRequest.getAppointVehicleId());
								//hsmwOrderVehicleRelation.setDriverName(checkedDriverSortVO.);
								hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
								hsmwOrderVehicleRelation.setOrderId(order.getId());
								HsmwVehicle hsmwVehicle =vehicle;
								hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
								hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
								hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
								hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
								hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
								//hsmwOrderVehicleRelation.setReachTime(hsmwOrderVehicleRequest.getCreateTime());
								hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
								hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
								hsmwOrderVehicleRelation.setId(relationId);
								if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getOutsideLeasingFlag()) && CommonConstants.YES.equals(hsmwOrderVehicleRequest.getOutsideLeasingFlag())){
									hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
								}else {
									hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.NO);
								}
								hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.RECEIVED.getValue());
								//插入数据前 判断数据是否已经改变。
								if (hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
									hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
									HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
									record1.setOrderId(order.getId());
									record1.setName(hsmwVehicle.getVehiclePlate());
									record1.setUserType("");
									record1.setCreateTime(LocalDateTime.now());
									record1.setUsername(user.getUsername());
									record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
									record1.setOperContent("接单 接单车辆为" + hsmwVehicle.getVehiclePlate());
									hsmwPumpOperateRecordService.save(record1);
									//针对筛选后的可以派单司机进行派单
									///接单中的司机进行推送
									for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
										String userId1 = hsmwUserDriver.getUserId();
										HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
										if (hsmwUsers != null) {
											TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(), "order_status_2");
											String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
											SendSmsUtil.sendDriverSmsCode(appId, appKey, msg, orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
											SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(), hsmwUsers.getUsername(), textOrderTimeOut, smsSign, "13520391225");
											try {
												Long queryTime = System.currentTimeMillis();
												SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), hsmwUsers.getUsername(), voiceCode);
												Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
									//司机指派成功 则 将 司机状态改为 工作中
									hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
										hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
									});
									hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
									//司机抢单成功 则 将 司机状态改为  工作中
									hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
									hsmwVehicleService.updateById(hsmwVehicle);
								}
							}
						}
						return;
					}
				}else{
					//如果不是指定车辆的下单 则走正常的下单流程。
					java. time.Duration duration = java.time.Duration.between(LocalDateTime.now(),  hsmwOrderVehicleRequest.getReachTime());
					//自营车辆的派单vo
					List<DriverUserSortVo> selfrunUserSortVos = new ArrayList<>();
					//合作公司的派单VO
					List<DriverUserSortVo> corperateDriverUserSortVos = new ArrayList<>();
					//平台的其他的公司的派单VO
					List<DriverUserSortVo> platformDriverUserSortVos = new ArrayList<>();
					//选中的司机信息
					DriverUserSortVo checkedDriverSortVO = null;

					//自营车辆的司机列表
					List<HsmwVehicle> selfrunVehicles = new ArrayList<>();
					//合作公司的司机列表
					List<HsmwVehicle> corperateVehicles = new ArrayList<>();
					//平台的其他的公司的司机列表
					List<HsmwVehicle> platformVehicles = new ArrayList<>();

					HsmwHtnUser createUser = hsmwHtnUserMapper.selectById(order.getCreateUser());
					//如果是公司用户 那么直接查询本公司的车辆作为自营车辆
					String selfrunCompanyId ="";
					if(HtnUserTypeEnum.COMPANY.getValue().equals(createUser.getType())){
						selfrunCompanyId= createUser.getOwnCompanyId();
					}
					//如果是搅拌站用户  则查询自营合作公司的Id
					if(HtnUserTypeEnum.CONCRETE.getValue().equals(createUser.getType())){
						List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(new LambdaQueryWrapper<HsmwCorporationCompany>()
								.eq(HsmwCorporationCompany::getConcretePlantId,createUser.getOwnCompanyId())
								.eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
						if(CollectionUtil.isNotEmpty(corporationCompanies)){
							selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
						}
					}
					//查询该项目绑定的泵送公司
					String itemCreateUserCompanyId=null;
					HsmwHtnUser itemCreator =null;
					if(HtnUserTypeEnum.FOREMAN.getValue().equals(createUser.getType())){
						HsmwItem item = hsmwItemService.getHsmwItemById(order.getItemId());
						itemCreator = hsmwHtnUserService.getHsmwUserById(item.getCreateUser());
						itemCreateUserCompanyId=itemCreator.getOwnCompanyId();
						if(StringUtils.isNotNull(itemCreator)){
							if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
								selfrunCompanyId= itemCreator.getOwnCompanyId();
							}
							//如果是搅拌站用户  则查询自营合作公司的Id
							if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
								List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(
										new LambdaQueryWrapper<HsmwCorporationCompany>()
												.eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId())
												.eq(HsmwCorporationCompany::getCorperateType, CorperateTypeEnum.SELFRUN.getValue()));
								if(CollectionUtil.isNotEmpty(corporationCompanies)){
									selfrunCompanyId= corporationCompanies.get(0).getCorperateCompanyId();
								}
							}
						}
					}
					//当指定车辆的ID不为空的时候
					if(StringUtils.isNotBlank(selfrunCompanyId)){
						hsmwOrderVehicleRequest.setLeasingCompanyId(selfrunCompanyId);
						selfrunVehicles = hsmwOrderService.getVehicleListByRequestId(hsmwOrderVehicleRequest,"1",createUser,itemCreateUserCompanyId,itemCreator);
					}
					//租赁公司和搅拌站查询合作的公司的车辆
					corperateVehicles = hsmwOrderService.getVehicleListByRequestId(hsmwOrderVehicleRequest,"2",createUser,itemCreateUserCompanyId,itemCreator);
					// 查询平台的车辆 的车辆
					//只有开启了平台叫泵的才会查询平台车辆
					//获取订单的创建人
					HsmwHtnUser hsmwUser = hsmwHtnUserMapper.selectById(order.getCreateUser());
					if(CommonConstants.YES.equals(order.getIfSelfChoose()) /*|| HtnUserTypeEnum.FOREMAN.getValue().equals(hsmwUser.getType())*/){
						platformVehicles = hsmwOrderService.getVehicleListByRequestId(hsmwOrderVehicleRequest,"3",createUser,itemCreateUserCompanyId,itemCreator);
					}
					//筛选 查询出来的自营车辆
					if(StringUtils.isListNotNull(selfrunVehicles)) {
						String imeiStrs = "";
						String vehicleIds = "";
						for (HsmwVehicle vehicle : selfrunVehicles) {
							if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
								imeiStrs += ("," + vehicle.getImeiNum());
								vehicleIds += ("," + vehicle.getIdentifyingCode());
							}
						}
						//查询车辆是否能到
						List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
						if (StringUtils.isNotBlank(imeiStrs)) {
							gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
						}
						List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

						for (HsmwVehicle hsmwVehicle :selfrunVehicles) {
							List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
									list(new LambdaQueryWrapper<HsmwRequestVehicle>()
											.eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
													eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
							if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
								continue;
							}
							// 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
							HashMap param = new HashMap();
							param.put("vehicleId", hsmwVehicle.getId());
							List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
							if(CollectionUtil.isEmpty(hsmwUserDrivers)){
								continue;
							}

							String vehicleId = hsmwVehicle.getId();
							DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
							driverUserSortVo.setVehicleId(vehicleId);
							//查询距离时间
							String vehicleLocalteInfo = null;
							String destinationLocateInfo = order.getLng() + "," + order.getLat();
							if (finalGpsInfoEntities.size() > 0) {
								for (GpsInfoEntity entity : finalGpsInfoEntities) {
									if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || entity.getDeviceId().equals(hsmwVehicle.getIdentifyingCode())) {
										if (StringUtils.isNotBlank(entity.getGpsLat())) {
											vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
										}
										break;
									}
								}
								if (StringUtils.isBlank(vehicleLocalteInfo)) {
									vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
								}
							}
							if (StringUtils.isBlank(vehicleLocalteInfo)) {
								vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
							}
							if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
								HashMap calculateParam = new HashMap();
								calculateParam.put("origin", vehicleLocalteInfo);
								calculateParam.put("destination", destinationLocateInfo);
								Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
								long sconds = duration.toMillis() / 1000;
								if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
									continue;
								}
								driverUserSortVo.setMobileLocate(durationTime);
							} else {
								//如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
								driverUserSortVo.setMobileLocate(100000000000L);
							}
							HsmwItem hsmwItem = hsmwItemService.getHsmwItemById(order.getItemId());
							HsmwUserDriver driver = hsmwUserDrivers.get(0);
							//user 信息
							String userId = driver.getUserId();
							HsmwDriverUser hsmwUserInfo = hsmwDriverUserMapper.selectById(userId);
							driverUserSortVo.setDriverList(hsmwUserDrivers);
							driverUserSortVo.setDriverId(driver.getId());
							driverUserSortVo.setHsmwOrder(order);
							driverUserSortVo.setHsmwVehicle(hsmwVehicle);
							driverUserSortVo.setHsmwUser(hsmwUserInfo);
							driverUserSortVo.setScore(driver.getScore());
							driverUserSortVo.setVehicleUnit(0);
							selfrunUserSortVos.add(driverUserSortVo);
						}
					}
					if(CollectionUtil.isNotEmpty(selfrunUserSortVos)){
						selfrunUserSortVos = sortDriverUserSort(selfrunUserSortVos);
						checkedDriverSortVO = selfrunUserSortVos.get(0);
						checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.SELFRUN.getValue());
					}else {
						//筛选 查询出来的平台车辆
						if(StringUtils.isListNotNull(corperateVehicles)) {
							String imeiStrs = "";
							String vehicleIds = "";
							for (HsmwVehicle vehicle : corperateVehicles) {
								if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
									imeiStrs += ("," + vehicle.getImeiNum());
									vehicleIds += ("," + vehicle.getIdentifyingCode());
								}
							}
							//查询车辆是否能到
							List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
							if (StringUtils.isNotBlank(imeiStrs)) {
								gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
							}
							List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

							for (HsmwVehicle hsmwVehicle :corperateVehicles) {
								List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
										list(new LambdaQueryWrapper<HsmwRequestVehicle>()
												.eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
														eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
								if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
									continue;
								}
								// 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
								HashMap param = new HashMap();
								param.put("vehicleId", hsmwVehicle.getId());
								List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
								if(CollectionUtil.isEmpty(hsmwUserDrivers)){
									continue;
								}

								String vehicleId = hsmwVehicle.getId();
								DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
								driverUserSortVo.setVehicleId(vehicleId);
								//查询距离时间
								String vehicleLocalteInfo = null;
								String destinationLocateInfo = order.getLng() + "," + order.getLat();
								if (finalGpsInfoEntities.size() > 0) {
									for (GpsInfoEntity entity : finalGpsInfoEntities) {
										if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
											if (StringUtils.isNotBlank(entity.getGpsLat())) {
												vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
											}
											break;
										}
									}
									if (StringUtils.isBlank(vehicleLocalteInfo)) {
										vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
									}
								}
								if (StringUtils.isBlank(vehicleLocalteInfo)) {
									vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
								}
								if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
									HashMap calculateParam = new HashMap();
									calculateParam.put("origin", vehicleLocalteInfo);
									calculateParam.put("destination", destinationLocateInfo);
									Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
									long sconds = duration.toMillis() / 1000;
									if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
										continue;
									}
									driverUserSortVo.setMobileLocate(durationTime);
								} else {
									//如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
									driverUserSortVo.setMobileLocate(100000000000L);
								}
								HsmwUserDriver driver = hsmwUserDrivers.get(0);
								//user 信息
								String userId = driver.getUserId();
								HsmwDriverUser hsmwUserInfo = hsmwDriverUserMapper.selectById(userId);
								driverUserSortVo.setDriverList(hsmwUserDrivers);
								driverUserSortVo.setDriverId(driver.getId());
								driverUserSortVo.setHsmwOrder(order);
								driverUserSortVo.setHsmwVehicle(hsmwVehicle);
								driverUserSortVo.setHsmwUser(hsmwUserInfo);
								driverUserSortVo.setScore(driver.getScore());
								driverUserSortVo.setVehicleUnit(0);
								corperateDriverUserSortVos.add(driverUserSortVo);
							}
						}
						if(CollectionUtil.isNotEmpty(corperateDriverUserSortVos)){
							corperateDriverUserSortVos = sortDriverUserSort(corperateDriverUserSortVos);
							checkedDriverSortVO=corperateDriverUserSortVos.get(0);
							checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.CORPERATE.getValue());

						}else{
							//筛选 查询出来的平台车辆
							if(StringUtils.isListNotNull(platformVehicles)) {
								String imeiStrs = "";
								String vehicleIds = "";
								for (HsmwVehicle vehicle : platformVehicles) {
									if (StringUtils.isNotBlank(vehicle.getImeiNum()) || StringUtils.isNotBlank(vehicle.getIdentifyingCode())) {
										imeiStrs += ("," + vehicle.getImeiNum());
										vehicleIds += ("," + vehicle.getIdentifyingCode());
									}
								}
								//查询车辆是否能到
								List<GpsInfoEntity> gpsInfoEntities = new ArrayList<>();
								if (StringUtils.isNotBlank(imeiStrs)) {
									gpsInfoEntities = GaoDeInfoUtils.getVehicleGpsLocate(imeiStrs,vehicleIds);
								}
								List<GpsInfoEntity> finalGpsInfoEntities = gpsInfoEntities;

								for (HsmwVehicle hsmwVehicle :platformVehicles) {
									List<HsmwRequestVehicle> hsmwRequestVehicles = hsmwRequestVehicleService.
											list(new LambdaQueryWrapper<HsmwRequestVehicle>()
													.eq(HsmwRequestVehicle::getVehilceId, hsmwVehicle.getId()).
															eq(HsmwRequestVehicle::getForemanUserId, order.getItemId()));
									if (CollectionUtil.isNotEmpty(hsmwRequestVehicles)) {
										continue;
									}
									// 查询接单中的司机 信息 如果没有接单中的司机那么 就不会进行派单
									HashMap param = new HashMap();
									param.put("vehicleId", hsmwVehicle.getId());
									List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverService.selectAvaliableList(hsmwVehicle.getId());
									if(CollectionUtil.isEmpty(hsmwUserDrivers)){
										continue;
									}
									String vehicleId = hsmwVehicle.getId();
									DriverUserSortVo driverUserSortVo = new DriverUserSortVo();
									driverUserSortVo.setVehicleId(vehicleId);
									//查询距离时间
									String vehicleLocalteInfo = null;
									String destinationLocateInfo = order.getLng() + "," + order.getLat();
									if (finalGpsInfoEntities.size() > 0) {
										for (GpsInfoEntity entity : finalGpsInfoEntities) {
											if (entity.getDeviceId().equals(hsmwVehicle.getImeiNum()) || StringUtils.equals(entity.getDeviceId(),hsmwVehicle.getIdentifyingCode())) {
												if (StringUtils.isNotBlank(entity.getGpsLat())) {
													vehicleLocalteInfo = entity.getGpsLon() + "," + entity.getGpsLat();
												}
												break;
											}
										}
										if (StringUtils.isBlank(vehicleLocalteInfo)) {
											vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
										}
									}
									if (StringUtils.isBlank(vehicleLocalteInfo)) {
										vehicleLocalteInfo = hsmwVehicle.getMobileLocate();
									}
									if (StringUtils.isNotBlank(vehicleLocalteInfo)) {
										HashMap calculateParam = new HashMap();
										calculateParam.put("origin", vehicleLocalteInfo);
										calculateParam.put("destination", destinationLocateInfo);
										Long durationTime = GaoDeInfoUtils.calculateDistanceTime(calculateParam);
										long sconds = duration.toMillis() / 1000;
										if ((float) sconds / 3600 < ((float) durationTime / 3600)) {
											continue;
										}
										driverUserSortVo.setMobileLocate(durationTime);
									} else {
										//如果通过gps的获取的距离为空  那么  车不可用，直接将距离设置为无限大
										driverUserSortVo.setMobileLocate(100000000000L);
									}
									HsmwItem hsmwItem = hsmwItemService.getHsmwItemById(order.getItemId());
									//user 信息
									HsmwUserDriver driver = hsmwUserDrivers.get(0);
									String userId = driver.getUserId();
									HsmwDriverUser hsmwUserInfo = hsmwDriverUserMapper.selectById(userId);
									driverUserSortVo.setDriverList(hsmwUserDrivers);
									driverUserSortVo.setDriverId(driver.getId());
									driverUserSortVo.setHsmwOrder(order);
									driverUserSortVo.setHsmwVehicle(hsmwVehicle);
									driverUserSortVo.setHsmwUser(hsmwUserInfo);
									driverUserSortVo.setScore(driver.getScore());
									driverUserSortVo.setVehicleUnit(0);
									platformDriverUserSortVos.add(driverUserSortVo);
								}
							}
							if(CollectionUtil.isNotEmpty(platformDriverUserSortVos)){
								platformDriverUserSortVos =sortDriverUserSort(platformDriverUserSortVos);
								checkedDriverSortVO= platformDriverUserSortVos.get(0);
								checkedDriverSortVO.setVehicleOwnType(VehicleTypeEnum.PLATEFORM.getValue());
							}
						}
					}
					//经过筛选，如果没有合适的司机就不进行派单
					if(StringUtils.isNotNull(checkedDriverSortVO)){
						//如果该需求有合适的车 那么就把该需求的状态改为 已发布
						hsmwOrderVehicleRequest.setRequestStatus(DistributeStatusEnum.RELEASED.getValue());
						//如果hsmwOrderVehicleRequest 更新成功 那么直接进行子订单和司机相关的操作
						if(hsmwOrderVehicleRelationService.checkIfVehicleWorking(checkedDriverSortVO.getVehicleId())){
							//创建子订单信息
							HsmwOrderVehicleRelation hsmwOrderVehicleRelation  = new HsmwOrderVehicleRelation();
							String  relationId = CommonUtils.generateId(hsmwOrderVehicleRelation);
							hsmwOrderVehicleRelation.setVehicleId(checkedDriverSortVO.getVehicleId());
							hsmwOrderVehicleRelation.setOrderStatus(ChildOrderStatusEnum.RECEIVED.getValue());
							hsmwOrderVehicleRelation.setOrderId(order.getId());
							HsmwVehicle hsmwVehicle = checkedDriverSortVO.getHsmwVehicle();
							hsmwOrderVehicleRelation.setImeiNum(hsmwVehicle.getImeiNum());
							hsmwOrderVehicleRelation.setVehicleNum(hsmwVehicle.getVehiclePlate());
							hsmwOrderVehicleRelation.setVehicleType(hsmwVehicle.getVehicleType());
							hsmwOrderVehicleRelation.setVehicleModel(hsmwVehicle.getVehicleModel());
							hsmwOrderVehicleRelation.setOrderVehicleRequestId(hsmwOrderVehicleRequest.getId());
							hsmwOrderVehicleRelation.setExpectVolume(hsmwOrderVehicleRequest.getExpectVolume());
							hsmwOrderVehicleRelation.setAcceptOrderTime(LocalDateTime.now());
							hsmwOrderVehicleRelation.setId(relationId);
							if(VehicleTypeEnum.PLATEFORM.getValue().equals(checkedDriverSortVO.getVehicleOwnType()) ){
								hsmwOrderVehicleRelation.setOutsideLeasingFlag(CommonConstants.YES);
							}
							//插入数据前 判断数据是否已经改变。
							if(hsmwOrderVehicleRequestService.compareAndUpdate(hsmwOrderVehicleRequest)) {
								hsmwOrderVehicleRelationService.save(hsmwOrderVehicleRelation);
								HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
								record1.setOrderId(order.getId());
								record1.setName(hsmwVehicle.getVehiclePlate());
								record1.setUserType("");
								record1.setCreateTime(LocalDateTime.now());
								record1.setUsername(user.getUsername());
								record1.setOrderStatus(PumpOrderStatusEnum.RECEIVED.getValue());
								record1.setOperContent("接单 接单车辆为"+hsmwVehicle.getVehiclePlate());
								hsmwPumpOperateRecordService.save(record1);
								//针对筛选后的可以派单司机进行派单
								//改车绑定的可用司机列表
								List<HsmwUserDriver> hsmwUserDriverList =checkedDriverSortVO.getDriverList();
								///接单中的司机进行推送
								if(CollectionUtil.isNotEmpty(hsmwUserDriverList)){
									try {
										HsmwDriverUser user1 = hsmwDriverUserMapper.selectById(hsmwUserDriverList.get(0).getUserId());
										SingleCallByVoiceResponse singleCallByVoiceResponse = Sample.SingleCallByVoice(Sample.createDyvmsapiClient(), user1.getUsername(), voiceCode);
										HsmwMonitorDriverMessage hsmwMonitorDriverMessage = new HsmwMonitorDriverMessage();
										hsmwMonitorDriverMessage.setOrderId(order.getId());
										hsmwMonitorDriverMessage.setRelationId(relationId);
										hsmwMonitorDriverMessage.setVehicleId(hsmwVehicle.getId());
										hsmwMonitorDriverMessage.setDirverPhone(user1.getUsername());
										hsmwMonitorDriverMessage.setCallId(singleCallByVoiceResponse.body.callId);
										hsmwMonitorDriverMessageMapper.insert(hsmwMonitorDriverMessage);
										//Sample.QueryCallDetailByCallId(Sample.createDyvmsapiClient(), singleCallByVoiceResponse.body.callId, queryTime);
									} catch (Exception e) {
										e.printStackTrace();
									}
									for (HsmwUserDriver hsmwUserDriver : hsmwUserDriverList) {
										String userId1 = hsmwUserDriver.getUserId();
										HsmwDriverUser hsmwUsers = hsmwDriverUserMapper.selectById(userId1);
										if(hsmwUsers != null){
											TencentPushUtils.pushMsg("系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！", hsmwUsers.getUsername(),"order_status_2");
											String msg = "系统已为您指派订单，请尽快前往APP查看，确认出发时间，以免延误工作！";
											SendSmsUtil.sendDriverSmsCode(appId, appKey, msg,orderTimeoutNoticeBiz, smsSign, hsmwUsers.getUsername());
											SendSmsUtil.sendBizOrderForceSms(appId, appKey, hsmwUsers.getName(),hsmwUsers.getUsername(),textOrderTimeOut, smsSign, "13520391225");
											HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
											hsmwDriverNews.setUserId(userId1);
											hsmwDriverNews.setMessage(msg);
											hsmwDriverNews.setAlreadyRead("0");
											hsmwDriverNewsService.save(hsmwDriverNews);
										}
									}
								}
								//司机指派成功 则 将 司机状态改为 工作中
								if (CollectionUtil.isNotEmpty(hsmwUserDriverList)){
									hsmwUserDriverList.stream().forEach(hsmwUserDriver -> {
										hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
									});
								}
								hsmwUserDriverService.updateBatchById(hsmwUserDriverList);
								//司机抢单成功 则 将 司机状态改为  工作中
								hsmwVehicle.setWorkStatus(CommonConstants.DRIVER_WORK);
								hsmwVehicleService.updateById(hsmwVehicle);
							}
						}
					}
				}
			});
		}

		Long end = System.currentTimeMillis();
		log.info("一次派单的所使用的时间长度是 " +(end-begin) +"ms");
		List<HsmwOrderVehicleRequest> expireTimerequestList = hsmwOrderVehicleRequestService.expireTimerequestList();
		if(CollectionUtil.isNotEmpty(expireTimerequestList)){
			expireTimerequestList.stream().forEach(hsmwOrderVehicleRequest -> {
				hsmwOrderVehicleRequest.setRequestStatus(RequestStatusEnum.INEFFECTIVE.getValue());
				//hsmwOrderVehicleRequest.setOperUserId();
				hsmwOrderVehicleRequest.setOperType(CommonConstants.YES);
				hsmwOrderVehicleRequest.setOperTime(LocalDateTime.now());
			});
			hsmwOrderVehicleRequestService.updateBatchById(expireTimerequestList);
			expireTimerequestList.stream().forEach(hsmwOrderVehicleRequest -> {
				HsmwHtnUser foremanUser  = hsmwHtnUserMapper.selectById(hsmwOrderVehicleRequest.getCreateUser());
				//进行推送和存入系统消息
				String message = "很抱歉，您的泵车订单暂时没有符合条件的空闲车辆，订单已被取消";
				String  foremanUserId = hsmwOrderVehicleRequest.getCreateUser();
				String  foremanUsername = foremanUser.getUsername();
				//新增系统消息
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setUserId(foremanUserId);
				hsmwDriverNews.setMessage(message);
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNewsService.save(hsmwDriverNews);

				HsmwPumpOperateRecord record1 = new HsmwPumpOperateRecord();
				record1.setOrderId(hsmwOrderVehicleRequest.getOrderId());
				record1.setUserType("");
				record1.setCreateTime(LocalDateTime.now());
				record1.setUsername(foremanUser.getUsername());
				record1.setOrderStatus(PumpOrderStatusEnum.CANCLED.getValue());
				record1.setOperContent("取消订单！");
				hsmwPumpOperateRecordService.save(record1);

				TencentPushUtils.pushForeManMsg(message,foremanUsername,"foreman_no_people");
				//TencentPushUtils.selfrunMsg(message,foremanUsername,"foreman_no_people");

			});
		}
	}

	/**
	 * 处理过期的混凝土订单
	 */
	//@Async("order")
	//@Scheduled(cron = "0 */1 * * * ?")
	//@Transactional
	public void executeExpireConcreteOrders() {
		List<HsmwOrder > expireConcreteOrders = hsmwOrderService.expireConcreteOrders();
		if(CollectionUtil.isNotEmpty(expireConcreteOrders)){
			List<HsmwOrderVehicleRequest> unprocessRequests= new ArrayList<>();
			expireConcreteOrders.stream().forEach(order -> {
				order.setOrderStatus(OrderStatusEnum.CANCELED.getValue());
				HsmwHtnUser createUser= hsmwHtnUserMapper.selectById(order.getCreateUser());
				//给工长推送信息 搅拌站拒绝接单的信息
				String msg = "您的混凝土订单被"+order.getConcretePlantName()+"拒绝，订单已被取消!";
				//新增系统消息
				HsmwDriverNews hsmwDriverNews = new HsmwDriverNews();
				hsmwDriverNews.setUserId(createUser.getId());
				hsmwDriverNews.setMessage(msg);
				hsmwDriverNews.setAlreadyRead("0");
				hsmwDriverNewsService.save(hsmwDriverNews);
				TencentPushUtils.pushForeManMsg(msg,createUser.getUsername(),"foreman_refuse_phone");
				TencentPushUtils.selfrunMsg(msg,createUser.getUsername(),"foreman_refuse_phone");
				List<HsmwOrderVehicleRequest> requests = hsmwOrderVehicleRequestService.list(new LambdaQueryWrapper<HsmwOrderVehicleRequest>()
						.eq(HsmwOrderVehicleRequest::getOrderId,order.getId()));
				requests.stream().forEach(request->{
					request.setRequestStatus(RequestStatusEnum.CANCELED.getValue());
				});
				unprocessRequests.addAll(requests);
			});
			hsmwOrderVehicleRequestService.updateBatchById(unprocessRequests);
			hsmwOrderService.updateBatchById(expireConcreteOrders);
		}
	}


	/**
	 * 处理24小时后的过期的取消订单记录c
	 */
	@Async("order")
	@Scheduled(cron = "0 */1 * * * ?")
	@Transactional
	public void executeExpireCancelOrderRecord() {
		 hsmwRequestVehicleService.expireCancelOrderRecord();
	}



	@Transactional
	public List<DriverUserSortVo> sortDriverUserSort(List<DriverUserSortVo> vos) {
		//如果选择的是
		Collections.sort(vos, new Comparator<DriverUserSortVo>() {
			@Override
			public int compare(DriverUserSortVo v1, DriverUserSortVo v2) {
				if (v2.getVehicleUnit() != (v1.getVehicleUnit())) {
					return (v2.getVehicleUnit() - v1.getVehicleUnit());
				} else {
					if(v2.getScore()!=v1.getScore()){
						return Integer.parseInt(v2.getScore()) - Integer.parseInt(v1.getScore());
					}else {
						return (int)(v1.getMobileLocate() -v2.getMobileLocate());
					}
				}
			}
		});
		return vos;
	}


	@Scheduled(cron = "0 0 10 * * ?")
	public void findRelationStatus() {
		List<HsmwOrderVehicleRelation> list = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderStatus, ChildOrderStatusEnum.UNDERREVIEW.getValue()));
		if(CollectionUtil.isNotEmpty(list)){
			String msg = "订单状态有误，请及时查看订单！";
			SendSmsUtil.sendDriverSmsCode(appId, appKey, msg,orderStatusIsSeven, smsSign, "17606405923");
		}

	}

}
